﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PaymentHelper
{
    public class PaymentStateCollection
    {
        private List<PaymentState> _listState = new List<PaymentState>();

        public void AddState(string token)
        {
            var state = new PaymentState() { 
               TimeOut = DateTime.UtcNow.AddMinutes(PaymentState.NumMiniutes),
               TokenPayment = token
            };

            _listState.Add(state);

            RemoveTimeOut();
        }

        public void RemoveState(string token)
        {
            int index = FindState(token);
            
            if (index != -1)
                _listState.RemoveAt(index);
        }

        public int FindState(string token)
        {
            for (int i = 0; i < _listState.Count; i ++)
            {
                if (_listState[i].TokenPayment.Equals(token, StringComparison.InvariantCultureIgnoreCase) 
                    && _listState[i].TimeOut.CompareTo(DateTime.UtcNow) >= 0)
                    return i;
            }

            return -1;
        }

        public PaymentState GetState(string token)
        {
            int index = FindState(token);

            return (index == -1) ? null : _listState[index];
        }

        public void UpdateState(string token, string urlProcess)
        {
            int index = FindState(token);
            if (index != -1)
                _listState[index].UrlProcessResult = urlProcess;
        }

        public void UpdateState(string token, PaymentResult result)
        {
            int index = FindState(token);
            if (index != -1)
                _listState[index].Result = result;
        }

        protected void RemoveTimeOut()
        {
            for (int i = 0; i < _listState.Count; i++)
            {
                var item = _listState.ElementAt(i);
                if (item.TimeOut.CompareTo(DateTime.UtcNow) < 0)
                {
                    _listState.Remove(item);
                }
            }
        }
    }
}
